package com.voice.server.channel.handle.impl;

import com.voice.core.entity.HttpHeader;
import com.voice.core.connection.Connection;
import com.voice.core.connection.ConnectionListener;
import com.voice.core.connection.ConnectionStatus;
import com.voice.core.connection.callback.AbstractStreamListener;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.server.channel.handle.StreamListenerHandler;
import com.voice.server.publish.PublishHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;


@Slf4j
public abstract class AbstractStreamListenerHandler<T extends Connection> extends AbstractStreamListener<T> implements StreamListenerHandler<T>, ConnectionListener<T>{

    @Override
    public void handle(HttpHeader requestHeader, Connection connection) throws Exception {
        T  t = conversionTo(requestHeader,connection);
        t.setDefaultStreamListener(this);
        t.setConnectionListener(this);
        t.setStatus(ConnectionStatus.AUTHORIZED);
    }

    public abstract T conversionTo(HttpHeader requestHeader, Connection connection) throws Exception;

    public PublishHandler getPublishHandler(String path){
        return null;
    }

    @Override
    public void onStreamRead(T connection, byte[] bytes) {

    }

    @Override
    public void onDataRead(T connection, Stream stream, StreamData streamData) {
        log.info(streamData.getHeaders().toString());
        HttpHeader requestHeader=streamData.getHeaders();
        PublishHandler publishHandler=getPublishHandler(requestHeader.path());
        if(publishHandler!=null) publishHandler.handle(stream,streamData,connection);
    }

}
